# draw.py
from pygame.locals import *

from config import *

# 初始化pygame
pygame.init()
window_width = WIDTH * CELL_SIZE + 200  # 增加宽度以显示分数
window_height = HEIGHT * CELL_SIZE
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((window_width, window_height))  # 设置窗口大小
pygame.display.set_caption('贪吃蛇')

# 设置字体
font = pygame.font.SysFont("Arial", 18)


def display_scores(score, high_score):
    """显示当前分数和历史最高分"""
    current_score_text = font.render(f"Score: {score}", True, WHITE)
    high_score_text = font.render(f"High Score: {high_score}", True, WHITE)

    # 计算换行后的位置
    score_line_height = current_score_text.get_height()

    # 显示当前分数
    playSurface.blit(current_score_text, (WIDTH * CELL_SIZE + 20, 30))

    # 显示历史最高分，位置调整到换行后的下一行
    playSurface.blit(high_score_text, (WIDTH * CELL_SIZE + 20, 10 + score_line_height + 60))


def draw_wall():
    """绘制墙壁"""
    for i in range(WIDTH):
        draw_cell(i, RED)
        draw_cell(i + (HEIGHT - 1) * WIDTH, RED)
    for i in range(HEIGHT):
        draw_cell(i * WIDTH, RED)
        draw_cell((i + 1) * WIDTH - 1, RED)

def draw_cell(position, color):
    """绘制单个方块，并添加边界"""
    x, y = CELL_SIZE * (position % WIDTH), CELL_SIZE * (position // WIDTH)
    pygame.draw.rect(playSurface, color, Rect(x, y, CELL_SIZE, CELL_SIZE))
    pygame.draw.rect(playSurface, BORDER_COLOR, Rect(x, y, CELL_SIZE, CELL_SIZE), 1)  # 添加边界

def draw_snake_and_food(snake, snake_size, food, score, high_score):
    """绘制蛇和食物，并显示分数"""
    playSurface.fill(BLACK)  # 清空整个屏幕
    draw_wall()  # 绘制墙壁
    draw_cell(food, GREEN)  # 绘制食物
    for i in range(snake_size):  # 绘制蛇
        color = HEAD_COLOR if i == 0 else WHITE
        draw_cell(snake[i], color)
    display_scores(score, high_score)  # 显示当前分数和历史最高分
    pygame.display.flip()